﻿using System;
using System.Linq;
using Roslyn.Compilers.CSharp;

namespace WeaverCustomTool
{
    public struct PropertyAttributeDeclaration
    {
        private readonly PropertyDeclarationSyntax property;

        public PropertyAttributeDeclaration(PropertyDeclarationSyntax property)
        {
            this.property = property;
        }

        /// <summary>
        /// Queries the first attribute of the type specified.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public AttributeSyntax FirstOfType<T>() where T: Attribute
        {
            var typeLongName = typeof (T).Name;
            var typeShortName = typeLongName.EndsWith("Attribute") 
                ? typeLongName.Substring(0, typeLongName.Length - "Attribute".Length)
                : typeLongName;
            return property.AttributeLists.
                   SelectMany(l => l.Attributes)
                   .FirstOrDefault(attr =>
                       {
                           var attributeName = attr.Name.ToFullString().Trim();
                           return attributeName == typeShortName || attributeName == typeLongName;
                       });
        }

        /// <summary>
        /// Determines whether the is any attribute of the type specified.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public bool AnyOfType<T>() where T : Attribute
        {
            var typeLongName = typeof(T).Name;
            var typeShortName = typeLongName.EndsWith("Attribute")
                ? typeLongName.Substring(0, typeLongName.Length - "Attribute".Length)
                : typeLongName;
            return property.AttributeLists.
                SelectMany(l => l.Attributes)
                .Select(attr => attr.Name.ToFullString().Trim())
                .Any(name => name == typeShortName || name == typeLongName);
        }
    }
}
